package com.health.mapp.impl;

import io.rong.models.TokenReslut;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.util.TextUtils;
import org.apache.log4j.Logger;

import com.health.commons.PropertiesService;
import com.health.db.dto.StuffDetailDto;
import com.health.db.model.UserLIST;
import com.health.db.model.UserLISTTemp;
import com.health.db.model.UserLoginJournal;
import com.health.db.service.msg.IUserLoginJournalService;
import com.health.db.service.sm.IRongService;
import com.health.db.service.sm.IWXService;
import com.health.db.service.user.IStuffListService;
import com.health.db.service.user.IUserLISTService;
import com.health.mapp.bean.Header;
import com.health.mapp.bean.SocialLoginReq;
import com.health.mapp.bean.SocialLoginResp;
import com.health.mapp.bean.WXTokenModel;
import com.health.mapp.utils.Constant;
import com.health.mapp.utils.DateUtils;
import com.health.mapp.utils.Response;
import com.health.mapp.utils.ResultCode;

import java.util.List;

public class SocialLoginImpl implements ActionInterface {

	private static Logger logger = Logger.getLogger(SocialLoginImpl.class);
	private IUserLISTService userLISTService;
	private IStuffListService stuffListService;
	private IRongService rongService;
	private IUserLoginJournalService userLoginJournalService;
	private IWXService wxService;

	boolean flag = false;

	@Override
	public Response execute(Header header, Object reqBean) throws Exception {
		// TODO Auto-generated method stub

		SocialLoginReq req = (SocialLoginReq) reqBean;
		SocialLoginResp _resp = new SocialLoginResp();
		_resp.setErrorCode(-1);
		_resp.setErrorMsg("登录失败");

		UserLIST user = null;
		if (1 == req.getLoginType()) {
			WXTokenModel tokenModel=null;
			if (!TextUtils.isEmpty(req.getWxCode())) {
				tokenModel = wxService.getAccessToken(req
						.getWxCode());
			}else if (TextUtils.isEmpty(req.getRefreshToken()))
			{
				//微信自动登录
				tokenModel =wxService.refreshToken(req.getRefreshToken());
			}

			if (null != tokenModel
					&& !TextUtils.isEmpty(tokenModel.getAccess_token())
					&& !TextUtils.isEmpty(tokenModel.getOpenid())) {

				List<UserLIST> userLISTS= userLISTService.selectByWXOpenid(tokenModel
						.getOpenid());
				if (null!=userLISTS&&userLISTS.size()>0) {

					user=userLISTS.get(0);
				}
				if (user == null) {
					// 没有通过openid查询到相关用户 通知客户端绑定手机号
					_resp.setRefreshToken(tokenModel.getRefresh_token());
					_resp.setWxToken(tokenModel.getAccess_token());
					_resp.setErrorCode(-100);
					_resp.setErrorMsg("没有关联到相关账号信息 请绑定手机号");
					return _resp;
				} else {
					
					UserLISTTemp userLIST = new UserLISTTemp();
					
					userLIST.setUserId(String.valueOf(user.getUserid()));
					userLIST.setUserName(user.getUserName());
					userLIST.setUserPhone(user.getUserNo());
					userLIST.setRegTime(user.getRegisterDate());
					userLIST.setIcon(user.getIconUrl());
					userLIST.setToken(user.getApptoken());
					userLIST.setUserTypeId(user.getTypeid());
					
					String iconUrl = userLIST.getIcon();
					// 如果是医生
					if (userLIST.getUserTypeId() == Constant.CONSTANTS_USER_ROLE_ID_3) {
						// docImage/kefu.png
						StuffDetailDto stuffDetailDto = stuffListService
								.selectByStuffId(user.getUserid());

						if (null != stuffDetailDto) {
							String docIconUrl = stuffDetailDto.getIconUrl();
							if (StringUtils.isNotBlank(docIconUrl)) {
								iconUrl = docIconUrl;
							} else {
								iconUrl = PropertiesService.getString(
										"iconUrl.docDefaultUrl").trim();
							}
						} else {
							_resp.setErrorCode(ResultCode.LOGIN_FAIL_MEMBER_IS_NOT_EXISTS);
							_resp.setErrorMsg(ResultCode.LOGIN_FAIL_MEMBER_IS_NOT_EXISTS_NOTE);
							return _resp;
						}
					} else {
						// 设置默认头像
						if (StringUtils.isBlank(iconUrl)) {
							iconUrl = PropertiesService.getString(
									"iconUrl.userDefaultUrl").trim();
						}
					}
					
					_resp.setUserId(String.valueOf(userLIST.getUserId()));
					_resp.setUser(userLIST);
					_resp.setWxToken(tokenModel.getAccess_token());
					_resp.setRefreshToken(tokenModel.getRefresh_token());
					buildResp(_resp, req, user);
				}

			} else {
				_resp.setErrorCode(-1);
				_resp.setErrorMsg("微信登录失败");
				return _resp;
			}
		}

		return _resp;
	}

	private void buildResp(SocialLoginResp _resp,SocialLoginReq req,UserLIST user) {
		UserLISTTemp userLIST = new UserLISTTemp();

		userLIST.setUserId(String.valueOf(user.getUserid()));
		userLIST.setUserName(user.getUserName());
		userLIST.setUserPhone(user.getUserNo());
		userLIST.setRegTime(user.getRegisterDate());
		userLIST.setIcon(user.getIconUrl());
		userLIST.setToken(user.getApptoken());

		userLIST.setUserTypeId(user.getTypeid());

		String iconUrl = userLIST.getIcon();
		// 更新登录信息
		UserLIST userLISTForUpdate = new UserLIST();

		// 如果是医生
		if (userLIST.getUserTypeId() == Constant.CONSTANTS_USER_ROLE_ID_3) {
			// docImage/kefu.png
			StuffDetailDto stuffDetailDto = stuffListService
					.selectByStuffId(user.getUserid());

			if (null != stuffDetailDto) {
				String docIconUrl = stuffDetailDto.getIconUrl();
				if (StringUtils.isNotBlank(docIconUrl)) {
					iconUrl = docIconUrl;
				} else {
					iconUrl = PropertiesService.getString(
							"iconUrl.docDefaultUrl").trim();
				}
			} else {
				_resp.setErrorCode(ResultCode.LOGIN_FAIL_MEMBER_IS_NOT_EXISTS);
				_resp.setErrorMsg(ResultCode.LOGIN_FAIL_MEMBER_IS_NOT_EXISTS_NOTE);
			}
		} else {
			// 设置默认头像
			if (StringUtils.isBlank(iconUrl)) {
				iconUrl = PropertiesService.getString("iconUrl.userDefaultUrl")
						.trim();
			}
		}

		if (StringUtils.isBlank(userLIST.getToken())) {
			/**
			 * token为空的话重新从融云获取Token
			 * */
			TokenReslut tokenReslut = rongService.getUserToken(String
					.valueOf(userLIST.getUserId()), userLIST.getUserName(),
					iconUrl);
			if (null != tokenReslut && tokenReslut.getCode() == 200) {
				// 更新user的AppToken
				userLISTForUpdate.setApptoken(tokenReslut.getToken());
				_resp.setErrorCode(ResultCode.OPERATION_SUCCESS);
				_resp.setErrorMsg("Success");
				_resp.setUserId(String.valueOf(userLIST.getUserId()));
				_resp.setToken(tokenReslut.getToken());
				_resp.setUser(userLIST);

			} else {
				_resp.setErrorCode(-1);
				_resp.setErrorMsg("获取Token失败");
			}
		} else {
			_resp.setErrorCode(ResultCode.OPERATION_SUCCESS);
			_resp.setErrorMsg("Success");
			_resp.setUserId(String.valueOf(userLIST.getUserId()));
			_resp.setToken(userLIST.getToken());
			_resp.setUser(userLIST);
		}

		userLISTForUpdate.setUserid(Long.valueOf(userLIST.getUserId()));
		userLISTForUpdate.setLoginDatetime(DateUtils.now());
		userLISTForUpdate.setUserNo(userLIST.getUserPhone());
		userLISTService.updateLoginInfo(userLISTForUpdate);

		UserLoginJournal loginJournal = new UserLoginJournal();

		loginJournal.setUserid(Long.valueOf(userLIST.getUserId()));
		loginJournal.setMachinedeviceid(req.getUuid());
		loginJournal.setLoginDatetime(DateUtils.now());

		if (null != req.getOs()) {
			loginJournal.setLoginFlag(Short.valueOf(req.getOs()));
		} else {
			loginJournal.setLoginFlag((short) 0);
		}
		userLoginJournalService.insert(loginJournal);
	}

	public IUserLISTService getUserLISTService() {
		return userLISTService;
	}

	public void setUserLISTService(IUserLISTService userLISTService) {
		this.userLISTService = userLISTService;
	}

	public IStuffListService getStuffListService() {
		return stuffListService;
	}

	public void setStuffListService(IStuffListService stuffListService) {
		this.stuffListService = stuffListService;
	}

	public IRongService getRongService() {
		return rongService;
	}

	public void setRongService(IRongService rongService) {
		this.rongService = rongService;
	}

	public IUserLoginJournalService getUserLoginJournalService() {
		return userLoginJournalService;
	}

	public void setUserLoginJournalService(
			IUserLoginJournalService userLoginJournalService) {
		this.userLoginJournalService = userLoginJournalService;
	}

	public IWXService getWxService() {
		return wxService;
	}

	public void setWxService(IWXService wxService) {
		this.wxService = wxService;
	}
	
	
}
